<?php
class home extends base{
  function __construct()
  {
    parent::__construct();
    $domain = explode('.' , $_SERVER['HTTP_HOST'] );
    // 安装系统之前无法链接数据库，下面代码会有误 
    $site = load('m/site_m')->get(" and domain = '".$domain['0']."'");
    $sid = $site[0]['uuid']?:'default';
    define(SID,$sid);
  }

  function index()
  {
    global $db_config;
    if(!isset($db_config)){
      $this->install();
      exit;
    }
    $this->page('home');
  }

  private function install()
  {
    global $db_config;
    if(is_array($db_config))redirect("?/");
    if($_POST){
      $_POST['default_db'] = $_POST['default_db'];
      $db = new db($_POST);
      $sql_file = APP.($_POST['setdemo'] ? 'demo.sql' : 'basic.sql');
      $sql = file_get_contents($sql_file);
      $db->muti_query($sql);
      $base_dir = rtrim($_POST['base_dir'],'/').'/';
      $seed = randstr();
      file_put_contents(APP.'config_user.php','<?
define(\'BASE\',\''.$base_dir.'?/\');
define(\'ADMIN_BASE\',BASE.\'?/admin/\');
define(\'SEED\',\''.$seed.'\');
$db_config = array(
  \'host\'      =>\''.$_POST['host'].'\',
  \'user\'      =>\''.$_POST['user'].'\',
  \'password\'  =>\''.$_POST['password'].'\',
  \'default_db\'=>\''.$_POST['default_db'].'\'
);');
      redirect($_POST['base_dir'],'安装成功');
    }
    else {
      header("Content-type: text/html; charset=utf-8");
      $param['page_title'] = '安装Alpaca4.0';
      $param['base'] = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']);
      $param['rewrite'] = in_array('mod_rewrite',apache_get_modules()) ? 1 : 0;
      $param['writable'] = ($this->is_writable('../app') && $this->is_writable('../app/v')) ? 1 : 0;
      $this->display("v/home/install",$param);
    }
  }

  private function is_writable($file) {
    if (is_dir($file)){
      $dir = $file;
      if ($fp = @fopen("$dir/test.txt", 'w')) {
        @fclose($fp);
        @unlink("$dir/test.txt");
        $writeable = 1;
      } else {
        $writeable = 0;
      }
    } else {
      if ($fp = @fopen($file, 'a+')) {
        @fclose($fp);
        $writeable = 1;
      } else {
        $writeable = 0;
      }
    }

    return $writeable;
  }

  function page($url = 'home'){

    global $tags;

    $node = load('m/node_m')->n('tags');

    $itms = _decode($node['ext']);
    foreach($itms as $it){
      $name = $it['name'];
      $tags[$name]=$it['val'];
    }
    $pages = load('m/node_m')->get(" and sid='".SID."' and  `name`='$url'");

    $ext1 = _decode($pages[0]['ext1']);
    $exts = explode("\n",$pages[0]['ext']);
    foreach($exts as $ext){
      $segs = explode(":",trim($ext));
      $pages[0][$segs[0]] = $segs[1];
    }
    $param = array_merge($pages[0],$ext1);
    $template = $ext1['template']?'v/temp/'.$ext1['template']:'v/layout/template';
    $layout = $ext1['layout']?'v/temp/'.$ext1['layout']:'v/layout/layout';
    $param['al_content'] = view($layout,$param,true);
    view($template,$param);
  }


  function reg(){
    $conf = array('email'=>'required|email','username'=>'required|isexist','password'=>'required');
    $err = validate($conf);
    if($_POST['password']!=$_POST['repassword']){
      $err['password']='两次密码不一样';
      $param['val'] = $_POST;
      $param['err'] = $err;
      $param['page_title'] = $param['meta_keywords'] = $param['meta_description'] = '注册';
      $this->display('v/user/register',$param);
    }elseif( $err === TRUE) {
      load('m/user_m')->register();
        redirect(BASE,'注册成功，请登录。');
    }else {
        $param['val'] = $_POST;
        $param['err'] = $err;
        $param['page_title'] = $param['meta_keywords'] = $param['meta_description'] = '注册';
        $this->display('v/user/register',$param);
    }
  }

  function login(){
    $rtu = isset($_GET['rtu'])?$_GET['rtu']:'/';
    $conf = array('username'=>'required','password'=>'required');
    $err = validate($conf);
    if (is_array($err)) {
      $err['info'] = $this->m->login_err;
      $param['err'] = $err;
      $param['page_title'] = $param['meta_keywords'] = $param['meta_description'] = '登录';
      $this->display('v/user/login',$param);
      exit;
    }

    if( load('m/user_m')->login( $_POST['username'] , $_POST['password'] )){
      redirect($rtu,'登录成功！');
      exit;
    }

    redirect('./?rtu='.$rtu,$this->m->login_err);
  }

  function logout(){
  	load('m/user_m')->logout();
    redirect(BASE,'退出登录！');
  }


}

function alpa($elem,$layout = 'list')
{
  global $tags;
  if(array_key_exists($elem,$tags))return $tags[$elem];

  $layout = $layout?'v/layout/'.$layout:'';
  $node = is_numeric($elem)?load('m/node_m')->get($elem):load('m/node_m')->n($elem);

  switch($node['type']){
    case 'link':
      $itms = _decode($node['ext']);
      return view($layout,array('itms'=>$itms),true);
      break;

    case 'page':
      $rs = load('m/node_m')->get(" and upid = '$node[id]' order by `order`,`id` asc");
      foreach($rs as $r){
        $itms[] = array('name'=>'p/'.$r['name'].'/','title'=>$r['title']);
      }
      return view($layout,array('itms'=>$itms),true);
      break;
  }
}


function alpa_list($elem,$layout = 'list')
{

  global $tags;
  if(array_key_exists($elem,$tags))return $tags[$elem];

  $layout = $layout?'v/layout/'.$layout:'';

  $node = is_numeric($elem)?load('m/node_m')->get($elem):load('m/node_m')->n($elem);
  $node_id = $node['id'];
  $node_sid = $node['sid'];
  $list = load('m/node_m')->get(" and `upid` = '$node_id' and `sid` = '$node_sid' order by `id`");
  foreach ($list as $k => $v) {
    $list[$k]['ext1'] = _decode($v['ext1']);
  }
  return view($layout,array('lists'=>$list),true);
}